              package com.java.diagnostics.visualizer.displayer.html;
              
              import com.java.diagnostics.visualizer.coredisplayers.util.Messages;
              import com.java.diagnostics.visualizer.data.AggregateData;
              import com.java.diagnostics.visualizer.data.DataPoint;
              import com.java.diagnostics.visualizer.data.DataSet;
              import com.java.diagnostics.visualizer.data.DomainData;
              import com.java.diagnostics.visualizer.data.StructuredData;
              import com.java.diagnostics.visualizer.data.TupleData;
              import com.java.diagnostics.visualizer.data.UnstructuredData;
              import com.java.diagnostics.visualizer.data.ids.ID;
              import com.java.diagnostics.visualizer.displayer.plot.LinePlotPreferenceHelper;
              import com.java.diagnostics.visualizer.exceptions.GCAndMemoryVisualizerException;
              import com.java.diagnostics.visualizer.impl.data.ids.TupleIDImpl;
              import com.java.diagnostics.visualizer.impl.display.DataDisplayerImpl;
              import com.java.diagnostics.visualizer.impl.factory.LogFactory;
              import com.java.diagnostics.visualizer.metadata.TupleMetaData;
              import com.java.diagnostics.visualizer.metadata.TupleMetaData.TableType;
              import com.java.diagnostics.visualizer.properties.IDsToDisplayProperties;
              import com.java.diagnostics.visualizer.properties.OutputProperties;

              import java.io.BufferedReader;
              import java.io.BufferedWriter;
              import java.io.File;
              import java.io.FileOutputStream;
              import java.io.FileWriter;
              import java.io.IOException;
              import java.io.InputStream;
              import java.io.InputStreamReader;
              import java.io.OutputStreamWriter;
              import java.text.MessageFormat;
              import java.util.Iterator;
              import java.util.logging.Level;
              import java.util.logging.Logger;
              
              public class HTMLReportDisplayer extends DataDisplayerImpl
              {
                private static final String PARAGRAPH_COMPLETE = "<p/>";
                private static final String ANCHOR_CLOSE = "</a>";
                private static final String ANCHOR_INTERNAL_OPEN = "<a href=\"#";
                private static final String HTML_CLOSE = "</html>";
                private static final String BODY_CLOSE = "</body>";
                private static final String NEWLINE = System.getProperty("line.separator");
              
                private static final String MAIN_DIV_OPEN = NEWLINE + 
                  "<div class=\"main\">";
                private static final String DIV_CLOSE = "</div>";
                private static final String NAVIGATION_DIV_OPEN = NEWLINE + 
                  "<div class=\"navigation\">";
                private static final String BODY_OPEN = "<body>";
                private static final String HEAD_CLOSE = "</head>";
                private static final String CLOSE_ANGLE_BRACKET = "\">";
                private static final String STYLESHEET_LINK = NEWLINE + 
                  "<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" media=\"{1}\"\\>" + NEWLINE;
                private static final String TITLE_OPEN = "<title>";
                private static final String HEADER = "<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset={0}\">";
                private static final String TITLE_CLOSE = "</title>";
                private static final String INDEX_HTML = "index.html";
                private static final String TMP_DIRECTORY_PREFIX = "gcmemoryvisualizerhtml";
                private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
                private static final String EMPTY_STRING = "";
                private static final String SPACE = " ";
                private static final String STYLESHEET = "report.css";
                private static final String PRINT_STYLESHEET = "print.css";
                private static final Logger TRACE = LogFactory.getTrace(HTMLReportDisplayer.class);
              
                private DataSet dataSet = null;
                private File directory;
                private OutputProperties outputProperties = null;
              
                public Object display(DataSet dataSet, OutputProperties outputProperties) {
                  TRACE.entering(this.className, "display");
              
          
                  this.directory = new File(System.getProperty("java.io.tmpdir"),"gcmemoryvisualizerhtml");
       

  
              
                  File[] victims = this.directory.listFiles();
                  boolean clearedDir = true;
                  if (victims != null) {
                    for (int i = 0; i < victims.length; i++) {
                      clearedDir |= victims[i].delete();
                    }
                  }
                  clearedDir |= this.directory.delete();
              
                  clearedDir |= this.directory.mkdir();
                  if (!clearedDir) {
                    TRACE.warning(MessageFormat.format(
                      Messages.getString("HTMLReportDisplayer.delete.failed"), new Object[] { 
                      this.directory.getAbsolutePath() }));
                  }
                  this.directory.deleteOnExit();
              
                  if (dataSet != null) {
                    this.dataSet = dataSet;
                    this.outputProperties = outputProperties;
                  }
                  Object answer;
                  if (dataSet != null)
                  {	            
                    answer = writeToString(dataSet.getCroppedDataSet(outputProperties), outputProperties);
                  }
                  else return null;
/*     *///          Object answer;
                  TRACE.exiting(this.className, "display");
                  return answer;
                }
              
                public void save(String name) throws GCAndMemoryVisualizerException
                {
                  TRACE.entering(this.className, "save");
              
                  if (name != null) {
                    this.directory = new File(name);
                    if ((this.directory.exists()) || (this.directory.mkdir())) {
                      writeToString(this.dataSet.getCroppedDataSet(this.outputProperties), this.outputProperties);
                    }
                  }
                  TRACE.exiting(this.className, "save");
                }
              
                public boolean isSaveAsDirectory() 
                {
                  return true;
                }
              
                private String writeToString(DataSet dataSet, OutputProperties outputProperties)
                {
                  LinePlotPreferenceHelper prefs = new LinePlotPreferenceHelper();
              // boolean drawDataLegend = prefs.getDrawDataLegend();
              //added by wenguang.huang 
               boolean drawDataLegend = true;
			  //added end by wenguang.huang 


               
              //prefs.setDrawDataLegend(false);
                  try
                  {
                    copyStylesheetToDestinationDirectory();
              
                    File file = new File(this.directory, "index.html");
              
                    UnstructuredDataWriter.initFiles(this.directory);
              
                    String charSet = "UTF-8";
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charSet));
              
                    writer
                      .write(MessageFormat.format("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset={0}\">", 
                      new Object[] { charSet }));
                    writer.write("<title>");
                    writer.write(Messages.getString("HTMLReportDisplayer.results"));
                    writer.write("</title>");
                    writer.write(
                      MessageFormat.format(STYLESHEET_LINK, new String[] { 
                      "report.css", "screen" }));
                    writer.write(
                      MessageFormat.format(STYLESHEET_LINK, new String[] { 
                      "print.css", "print" }));
                    writer.write("</head>");
                    writer.write("<body>");
                    writer.write(NAVIGATION_DIV_OPEN);
                    AggregateData representativeData = dataSet.getRepresentativeData();
                int length =0;
                //dataSet.getVariants();
//             representativeData.getStructuredData()[1].getID();
                    Iterator ids = outputProperties.getUnstructuredFieldsToDisplay().getAllIDsToDisplay();
               //added by wenguang.huang 2014年3月5日 下午4:23:52
               UnstructuredData[] unstructureddatas1 =  representativeData.getUnstructuredData();                 
                    length = unstructureddatas1.length;
                    for(int i=0;i<length;i++) {
                      ID id = unstructureddatas1[i].getID();      
                  addLink(representativeData, writer, id);
                    }
                //added end by wenguang.huang 2014年3月5日 下午4:23:52

   
                    addLinks(representativeData, writer, ids);
                    ids = outputProperties.getStructuredFieldsToDisplay().getAllIDsToDisplay();
                      
                    addLinks(representativeData, writer, ids);
                    IDsToDisplayProperties tupleFieldsToDisplay = outputProperties.getTupleFieldsToDisplay();
                      
                    ids = tupleFieldsToDisplay.getAllIDsToDisplay();
                    addLinks(representativeData, writer, ids);
                    writer.write("</div>");
              
                    writer.write(MAIN_DIV_OPEN);
                //outputProperties.getUnstructuredFieldsToDisplay().addID(arg0);
                // outputProperties.getUnstructuredFieldsToDisplay().addID();
/*    209 */    ids = outputProperties.getUnstructuredFieldsToDisplay().getAllIDsToDisplay();
                    UnstructuredData[] unstructureddatas =  representativeData.getUnstructuredData();                 
                    length = unstructureddatas.length;
                    for(int i=0;i<length;i++) {
                      ID id = unstructureddatas[i].getID();
                     
                      DataWriter dataWriter = new UnstructuredDataWriter(dataSet, representativeData, writer, id);
                        
                      dataWriter.write();
                    }
              
                    writer.write(NEWLINE);
                    writer.write(NEWLINE);
              
                   ids = outputProperties.getStructuredFieldsToDisplay().getAllIDsToDisplay();
                      
                   StructuredData[] structureddatas =representativeData.getStructuredData();
               length = structureddatas.length;
                    for(int i=0;i<length;i++){
                      ID id = (ID)structureddatas[i].getID();
                      
                      DataWriter dataWriter = new StructuredDataWriter(dataSet, 
                        representativeData, writer, id);
                      dataWriter.write();
                    }
         // tupleFieldsToDisplay.addID(new TupleIDImpl(null,"VGCLabels.objects.compacted"));
         // ids = tupleFieldsToDisplay.getAllIDsToDisplay();
                    //added by wenguang.huang 
                TupleData[] tupleDatas=representativeData.getTupleData();
                length =tupleDatas.length;
                //added end by wenguang.huang 


                    tupleFieldsToDisplay.disableNotifications();
                    // deleted by wenguang.huang 
                    //while (ids.hasNext()) {
                //added by wenguang.huang 
                for(int i=0;i<length;i++){
                      ID id = tupleDatas[i].getID();
				//added end by wenguang.huang 
                //TupleData tupleData = representativeData.getTupleData(id);
                //TupleData tupleData=representativeData.getTupleData("VGCLabels.objects.compacted");
               // DataPoint[] ddDataPoints=tupleData.getDataPoints();
                //TupleData[] tempDatas=representativeData.getTupleData();
                //int i =tempDatas.length;
                //String sa =tempDatas[0].getLabel();
                      if ((representativeData.getTupleData(id) != null) && (!representativeData.getTupleData(id).isEmpty())) {         
                        TupleMetaData metaData = representativeData.getTupleData(id).getTupleMetaData();        
                        TupleMetaData.TableType tupleTableType = TupleMetaData.TableType.NONE;
                        if ((metaData != null) && (metaData.getTableType() != null)) 
                    {
                          tupleTableType = metaData.getTableType();
                        }
                        DataWriter dataWriter = null;
                        switch (tupleTableType) {
                        case COUNT:
                          dataWriter = new CountTableTupleDataWriter(
                            dataSet, outputProperties, representativeData, 
                            writer, id, this.directory);
                          break;
                        case FREQUENCY:
                          dataWriter = new FrequencyTableTupleDataWriter(
                            dataSet, outputProperties, representativeData, 
                            writer, id, this.directory);
                          break;
                        case NONE:
                          dataWriter = new NoTableTupleDataWriter(
                            dataSet, outputProperties, representativeData, 
                            writer, id, this.directory);
                          break;
                        case ARITHMETIC:
                          dataWriter = new ArithmeticTableTupleDataWriter(
                            dataSet, outputProperties, representativeData, 
                            writer, id, this.directory);
                          break;
                        }
              
                        if (dataWriter != null) {
                          dataWriter.write();
                        }
                      }
                    }
              
                    tupleFieldsToDisplay.enableNotifications();
                   
                    writer.write(NEWLINE);
                    writer.write(NEWLINE);
                    writer.write("</div>");
              
                    writer.write("</body>");
                    writer.write("</html>");
                    writer.close();
                    return file.getAbsolutePath();
                  }
                  catch (Throwable e) {
                    TRACE.log(Level.WARNING, 
                      Messages.getString("HTMLReportDisplayer.caught.exception"), e);
                    return null;
                  }
                  finally {
                    //prefs.setDrawDataLegend(drawDataLegend);
                  }
                }
              
                private void addLinks(AggregateData representativeData, BufferedWriter writer, Iterator ids)
                  throws IOException
                {
	         
                  while (ids.hasNext()) {
                    ID id = (ID)ids.next();
                    DomainData data = representativeData.getData(id);
                    if ((data != null) && (!data.isEmpty())) {
                      writer.write(NEWLINE);
                      writer.write("<a href=\"#");
                      writer.write(stripSpaces(data.getLabel()));
                      writer.write("\">");
                      writer.write(data.getDisplayName());
                      writer.write("</a>");
                      writer.write("<p/>");
                    }
                  }
                }
              
          //added by wenguang.huang 2014年3月5日 下午4:22:46
                private void addLink(AggregateData representativeData, BufferedWriter writer, ID id)
                  throws IOException
                {
	        
                    DomainData data = representativeData.getData(id);
                    if ((data != null) && (!data.isEmpty())) {
                      writer.write(NEWLINE);
                      writer.write("<a href=\"#");
                      writer.write(stripSpaces(data.getLabel()));
                      writer.write("\">");
                      writer.write(data.getDisplayName());
                      writer.write("</a>");
                      writer.write("<p/>");    
                  }
                }
          //added end by wenguang.huang 2014年3月5日 下午4:22:46
                private void copyStylesheetToDestinationDirectory() throws IOException {
                  writeOutResource("report.css");
                  writeOutResource("print.css");
                }
              
                private void writeOutResource(String name) throws IOException {
                  InputStream stylesheet = getResource(name);
                  if (stylesheet != null) {
                    BufferedReader reader = null;
                    FileWriter writer = null;
                    try {
                      reader = new BufferedReader(new InputStreamReader(stylesheet));
                      File stylesheetCopy = new File(this.directory, name);
              
                      writer = new FileWriter(stylesheetCopy);
                      char[] buffer = new char[1024];
                      int len = reader.read(buffer, 0, 1024);
                      while (len > -1) {
                        writer.write(buffer, 0, len);
                        len = reader.read(buffer, 0, buffer.length);
                      }
                    } finally {
                      if (writer != null) {
                        writer.close();
                      }
                      if (reader != null)
                        reader.close();
                    }
                  }
                }
              
                private String stripSpaces(String string)
                {
                  return string.replaceAll(" ", "");
                }
              
                private InputStream getResource(String fileName) {
                  InputStream resource = HTMLReportDisplayer.class
                    .getResourceAsStream(fileName);
              
                  return resource;
                }
              
                public void dispose()
                {
	
                }
              
                public void print()
                  throws GCAndMemoryVisualizerException
                {
                }
              }

